package ru.digitanoise.dnimageapi.controllers;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.digitanoise.dnimageapi.models.FileAttachment;
import ru.digitanoise.dnimageapi.services.FileAttachmentService;
import java.util.Objects;

@RestController
@RequestMapping("/dn/image/internal/api/v1/")
@RequiredArgsConstructor
public class FileAttachmentController {

    private final FileAttachmentService fileAttachmentService;

    @PostMapping(name = "/save", consumes = {"multipart/form-data"})
    @ResponseBody
    public ResponseEntity<FileAttachment> uploadFile(
            @RequestPart(value = "avatar", required = false) MultipartFile avatar
    ) {
        if (Objects.equals(avatar.getContentType(), "image/jpg")) {
            return ResponseEntity.ok(
                    fileAttachmentService.saveAsJPG(avatar)
            );
        }

        if (Objects.equals(avatar.getContentType(), "image/png")) {
            return ResponseEntity.ok(
                    fileAttachmentService.saveAsPNG(avatar)
            );
        }

        return ResponseEntity.ofNullable(null);
    }

}
